<?php

namespace app\business\controller;

use app\business\model\AreasModel;
use app\resource\model\CurrencyModel;
use app\business\model\FollowModel;
use app\business\model\IndustryCateModel;
use app\business\model\LicensePlateModel;
use app\business\model\LicensePlateUserModel;
use app\department\model\UserModel;
use cmf\controller\AdminBaseController;

/**
 * Class LicensePlateController
 * @package app\business\controller
 * @adminMenuRoot(
 *     'name'   =>'业务管理',
 *     'action' =>'default',
 *     'parent' =>'',
 *     'display'=> true,
 *     'order'  => 30,
 *     'icon'   =>'th',
 *     'remark' =>'业务管理',
 * )
 */
class LicensePlateController extends AdminBaseController
{
    /**
     * 卖家列表
     * @adminMenu(
     *     'name'   => '卖家列表',
     *     'parent' => 'business/LicensePlate/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 100,
     *     'icon'   => '',
     *     'remark' => '卖家列表',
     *     'param'  => ''
     * )
     */
    function index()
    {
        $where = [];
        $uid = cmf_get_current_admin_id();
        if ($uid != 1) {
            $users = implode(',', getUsersForRole($uid));
            $where['clpuser.uid|mlpuser.uid'] = ['in', $users];
        }

        if (input('category')) {
            $where['cid'] = input('category');
        }
        if (input('start_time')) {
            $where['plate.createtime'] = ['gt', strtotime(input('start_time'))];
        }
        if (input('end_time')) {
            $endtime = strtotime(input('end_time'));
            $datetime = strtotime(date('Y-m-d',$endtime));
            if($endtime == $datetime) {
                $endtime += 86399;
            }
            if (isset($where['plate.createtime'])) {
                $where['plate.createtime'] = ['BETWEEN', [strtotime(input('start_time')), $endtime]];
            } else {
                $where['plate.createtime'] = ['lt', $endtime];
            }
        }
        if (input('keyword')) {
            $keyword = input('keyword');
            $where['company|plate.phone|cuser.user_nickname|muser.user_nickname'] = ['like', "%$keyword%"];
        }

        $plateModel = new LicensePlateModel();
        $lists = $plateModel
            ->alias('plate')
            ->join('__INDUSTRY_CATE__ platecate', 'plate.cid = platecate.id')
            ->join('__AREAS__ areas', 'plate.area = areas.areaid')
            ->join('__LICENSE_PLATE_USER__ clpuser', 'plate.id = clpuser.pid and clpuser.level = 1', 'left')//创建
            ->join('__LICENSE_PLATE_USER__ mlpuser', 'plate.id = mlpuser.pid and mlpuser.level = 2', 'left')//负责
//            ->join('__LICENSE_PLATE_USER__ slpuser', 'plate.id = slpuser.pid and slpuser.level = 3', 'left')//分享

            ->join('__USER__ cuser', 'clpuser.uid = cuser.id', 'left')
            ->join('__USER__ muser', 'mlpuser.uid = muser.id', 'left')
            ->field(['plate.*,platecate.name as cname,areas.name as aname',
                'cuser.user_nickname as cuname',
                'muser.user_nickname as muname',
            ])
            ->where($where)
            ->order('plate.createtime desc,plate.id desc')
            ->paginate();

        $licensePlateCate = new IndustryCateModel();
        $cate = $licensePlateCate->where([
            'status' => 1,
            'parent_id' => ['neq',0],
            'is_del' => 0
        ])->order('parent_id,list_order,id')->select();

        $where_r = input();
        $lists->appends($where_r);
        $page = $lists->render();

        $this->assign('lists', $lists);
        $this->assign('where_r', $where_r);
        $this->assign('page', $page);
        $this->assign('cate', $cate);

        return $this->fetch();
    }

    /**
     * 添加
     * @adminMenu(
     *     'name'   => '添加',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加',
     *     'param'  => ''
     * )
     */
    function add()
    {
        if ($this->request->isPost()) {
            $this->addPost();
        }
        $currency = new CurrencyModel();
        $defCurrency = $currency->where(['id' => 1])->find();

        $areas = new AreasModel();
        $areaslist = $areas->where(['parentid' => 0])->order('sort')->select()->toArray();

        $industryCateModel = new IndustryCateModel();
        $industryCate = $industryCateModel->where(['parent_id' => 0])->order('list_order')->select()->toArray();

        $this->assign('defCurrency', $defCurrency);
        $this->assign('areaslist', $areaslist);
        $this->assign('industryCate', $industryCate);
        return $this->fetch();
    }

    private function addPost()
    {
        $plateModel = new LicensePlateModel();
        $arrData = $this->request->post();

        $arrData['createtime'] = strtotime($arrData['createtime']);
        if (!$arrData['createtime']) {
            $arrData['createtime'] = time();
        }
        $arrData['regtime'] = strtotime($arrData['regtime']);
        if(!$arrData['manager']) {
            $arrData['manager'] = cmf_get_current_admin_id();
        }

        $result = $plateModel->allowField(true)->validate(true)->save($arrData);
        if ($result) {
            //$plateModel->where(['id' => $plateModel->id])->update(['no' => 'PRO' . ($plateModel->id + 1853850)]);
            $licensePlateUserModel = new LicensePlateUserModel();
            $licensePlateUserModel->allowField(true)->saveAll([
                ['pid' => $plateModel->id, 'uid' => cmf_get_current_admin_id(), 'level' => 1],
                ['pid' => $plateModel->id, 'uid' => $arrData['manager'], 'level' => 2],
            ]);
            $this->success(lang("ADD_SUCCESS"), url("LicensePlate/index"));
        } else {
            $this->error($plateModel->getError());
        }

    }

    /**
     * 编辑
     * @adminMenu(
     *     'name'   => '编辑',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑',
     *     'param'  => ''
     * )
     */
    function edit()
    {
        if ($this->request->isPost()) {
            $this->editPost();
        }
        $id = $this->request->param('id', 0, 'intval');
        $licensePlateModel = new LicensePlateModel();
        $result = $licensePlateModel
            ->alias('plate')
            ->join('__INDUSTRY_CATE__ platecate', 'plate.cid = platecate.id', 'left')
            ->join('__AREAS__ areas', 'plate.area = areas.areaid', 'left')
            ->join('__USER__ user', 'plate.manager = user.id', 'left')
            ->join('__CURRENCY__ currency', 'plate.currency = currency.id', 'left')
            ->join('__CUSTOMER_NATURE__ nature', 'plate.nature = nature.id', 'left')
            ->field([
                'plate.*,platecate.name as cname,areas.name as aname,user.user_nickname as sname,currency.name as currname',
                'nature.name as nature_name'
            ])
            ->where(['plate.id' => $id])->find();

        $areas = new AreasModel();
        $areaslist = $areas->where(['parentid' => 0])->order('sort')->select()->toArray();


        //分类信息
        $incates = new IndustryCateModel();
        $catelist = $incates->where(['parent_id' => 0])->select()->toArray();
        $cateinfo = $incates->where(['id' => $result['cid']])->find();
        $parentcateinfo = $incates->where(['parent_id' => $cateinfo['parent_id']])->select()->toArray();
        $this->assign('areaslist', $areaslist);
        $this->assign('result', $result);
        $this->assign('catelist', $catelist);
        $this->assign('cateinfo', $cateinfo);
        $this->assign('parentcateinfo', $parentcateinfo);

        return $this->fetch();
    }

    private function editPost()
    {
        $plateModel = new LicensePlateModel();
        $arrData = $this->request->post();

        $arrData['regtime'] = strtotime($arrData['regtime']);
        $arrData['createtime'] = strtotime($arrData['createtime']);
        if (!$arrData['createtime']) {
            $arrData['createtime'] = time();
        }

        $result = $plateModel->allowField(true)->validate(true)->save($arrData, ["id" => $arrData["id"]]);
        if ($result) {
            $licensePlateUserModel = new LicensePlateUserModel();
            $licensePlateUserModel->allowField(true)->save([
                'uid' => $arrData['manager']
            ], ['pid' => $arrData['id'], 'level' => 2]);
            $this->success(lang("EDIT_SUCCESS"), url("LicensePlate/index"));
        }else{
            $this->error($plateModel->getError());
        }
    }


    function getCate()
    {
        $IndustryModel = new IndustryCateModel();
        $arrData['parent_id'] = $this->request->param('id', 0, 'intval');
        $arrData['is_del'] = 0;
        $res = $IndustryModel->where($arrData)->select();
        echo json_encode($res);
        exit;

    }

    /**
     * 卖家跟进
     * @adminMenu(
     *     'name'   => '卖家跟进',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '卖家跟进',
     *     'param'  => ''
     * )
     */
    function follow()
    {
        $pid = $this->request->param('pid', 0, 'intval');
        if(!$pid) {
            $this->error('非法访问');
        }
        $followModel = new FollowModel();
        $where = ['type' => 1, 'pid' => $pid];
        $lists = $followModel
            ->alias('follow')
            ->join('__USER__ user', 'follow.uid = user.id')
            ->field('follow.*,user.user_nickname as uname')
            ->where($where)
            ->order(['id desc'])
            ->paginate(10);
        $page = $lists->render();

        $this->assign('lists', $lists);
        $this->assign('page', $page);
        $this->assign('pid', $pid);
        return $this->fetch();
    }

    /**
     * 添加卖家跟进
     * @adminMenu(
     *     'name'   => '添加卖家跟进',
     *     'parent' => 'follow',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加卖家跟进',
     *     'param'  => ''
     * )
     */
    function add_follow()
    {
        $pid = $this->request->param('pid', 0, 'intval');
        if(!$pid) {
            $this->error('非法访问');
        }
        $this->assign('pid', $pid);
        return $this->fetch();
    }

    /**
     * 添加卖家跟进提交
     * @adminMenu(
     *     'name'   => '添加卖家跟进提交',
     *     'parent' => 'follow',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加卖家跟进提交',
     *     'param'  => ''
     * )
     */
    function add_followPost()
    {
        $followModel = new FollowModel();
        $arrData = $this->request->post();

        $time = time();
        $arrData['create_time'] = $time;
        $arrData['type'] = 1;
        $arrData['uid'] = cmf_get_current_admin_id();
        $arrData['next_time'] = strtotime($arrData['next_time']);
        if ($arrData['next_time'] < $time) {
            $arrData['next_time'] = 0;
        }
        if(!$arrData['pid']) {
            $this->error('非法访问');
        }

        $result = $this->validate($arrData, 'Follow');
        if ($result !== true) {
            $this->error($result);
        }

        $result = $followModel->allowField(true)->insertGetId($arrData);
        if ($result) {
            $plateModel = new LicensePlateModel();
            $plateModel->where(['id' => $arrData['pid']])->update([
                'evolve' => $arrData['remark'],
                'newtime' => $time,
                'nexttime' => $arrData['next_time']
            ]);
        }

        $this->success(lang("ADD_SUCCESS"), url("LicensePlate/follow", ['pid' => $arrData['pid']]));
    }

    /**
     * 编辑卖家跟进
     * @adminMenu(
     *     'name'   => '编辑卖家跟进',
     *     'parent' => 'follow',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑卖家跟进',
     *     'param'  => ''
     * )
     */
    function edit_follow()
    {
        $id = $this->request->param('id', 0, 'intval');
        $followModel = new FollowModel();
        $result = $followModel->where(['id' => $id])->find();

        $this->assign('result', $result);
        return $this->fetch();
    }

    /**
     * 编辑卖家跟进提交
     * @adminMenu(
     *     'name'   => '编辑卖家跟进提交',
     *     'parent' => 'follow',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑卖家跟进提交',
     *     'param'  => ''
     * )
     */
    function edit_followPost()
    {
        $followModel = new FollowModel();
        $arrData = $this->request->post();

        $time = time();
        $arrData['next_time'] = strtotime($arrData['next_time']);
        if ($arrData['next_time'] < $time) {
            $arrData['next_time'] = 0;
        }

        $result = $this->validate($arrData, 'Follow.edit');
        if ($result !== true) {
            $this->error($result);
        }

        $result = $followModel->allowField(true)->where(["id" => $arrData["id"]])->update($arrData);
        if ($result) {
            $new = $followModel->where(['type' => 1, 'pid' => $arrData['pid']])->max('id');
            if ($new == $arrData['id']) {
                $plateModel = new LicensePlateModel();
                $plateModel->where(['id' => $arrData['pid']])->update([
                    'evolve' => $arrData['remark'],
                    'newtime' => $time,
                    'nexttime' => $arrData['next_time']
                ]);
            }
        }

        $this->success(lang("EDIT_SUCCESS"), url("LicensePlate/follow", ['pid' => $arrData['pid']]));
    }

    /**
     * 记录分配
     * @adminMenu(
     *     'name'   => '记录分配',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '记录分配',
     *     'param'  => ''
     * )
     */
    function allot()
    {
        $check_ids = $this->request->param('check_ids', '');
        $licensePlateUserModel = new LicensePlateUserModel();
        if ($this->request->isPost()) {
            $ids = $this->request->param('ids', 0, 'intval');
            $licensePlateUserModel->allowField(true)->save(['uid' => $ids], [
                'pid' => ['in', $check_ids],
                'level' => 2
            ]);
            $licensePlateModel = new LicensePlateModel();
            $licensePlateModel->save([
                'manager' => $ids
            ], [
                'id' => ['in', $check_ids],
            ]);

            $this->success('设置成功');
        } else {
            $where = [];
            $uid = cmf_get_current_admin_id();
            $flag = false;
            if ($uid != 1) {
                $roles = db('role_user')
                    ->where(['user_id' => $uid])
                    ->column('role_id');

                $role_deps = get_role_department($roles,'data_to_all_user');
                foreach ($role_deps as $role_dep) {
                    if ($role_dep['data_to_all_user']) {
                        $flag = true;
                    }
                }
            }

            if ($uid != 1 && !$flag) {
                $where['dep.id'] = ['in', getUsersGroup($uid)];
            }

            $userModel = new UserModel();

            $where['user_status'] = ['neq', 0];
            $lists = $userModel
                ->alias('user')
                ->join('__DEPARTMENT_USER__ dep_user', 'user.id = dep_user.user_id')
                ->join('__DEPARTMENT__ dep', 'dep_user.dep_id = dep.id')
                ->field([
                    'user.*',
                    'dep.name as dep_name,dep.id as dep_id'
                ])->where($where)->select();

            $users = $licensePlateUserModel->where([
                'pid' => ['in', $check_ids],
                'level' => 2
            ])->column('uid');

            $this->assign('lists', $lists);
            $this->assign('users', $users);
            return $this->fetch();
        }
    }

    /**
     * 记录分享
     * @adminMenu(
     *     'name'   => '记录分享',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '记录分享',
     *     'param'  => ''
     * )
     */
    function share()
    {
        $check_ids = $this->request->param('check_ids', '');
        $licensePlateUserModel = new LicensePlateUserModel();
        if ($this->request->isPost()) {
            $ids = $this->request->param('ids', '');
            $users = $licensePlateUserModel->where([
                'pid' => ['in', $check_ids],
                'level' => 3
            ])->select()->toArray();

            $licensePlateUserModel
                ->where([
                    'level' => 3,
                    'pid' => ['in', $check_ids]
                ])->delete();

            $ids = explode(',', $ids);
            $check_ids = explode(',', $check_ids);

            $data = [];
            foreach ($ids as $id) {
                foreach ($check_ids as $check_id) {
                    $data[] = [
                        'pid' => $check_id,
                        'uid' => $id,
                        'level' => 3
                    ];
                }
            }
            $licensePlateUserModel->allowField(true)->saveAll($data);
            $this->success('设置成功');
        } else {
            $where = [];
            $uid = cmf_get_current_admin_id();
            $flag = false;
            if ($uid != 1) {
                $roles = db('role_user')
                    ->where(['user_id' => $uid])
                    ->column('role_id');

                $role_deps = get_role_department($roles,'data_to_all_user');
                foreach ($role_deps as $role_dep) {
                    if ($role_dep['data_to_all_user']) {
                        $flag = true;
                    }
                }
            }

            if ($uid != 1 && !$flag) {
                $where['dep.id'] = ['in', getUsersGroup($uid)];
            }
            $where['user_status'] = ['neq', 0];

            $userModel = new UserModel();

            $lists = $userModel
                ->alias('user')
                ->join('__DEPARTMENT_USER__ dep_user', 'user.id = dep_user.user_id')
                ->join('__DEPARTMENT__ dep', 'dep_user.dep_id = dep.id')
                ->field([
                    'user.*',
                    'dep.name as dep_name,dep.id as dep_id'
                ])->where($where)->select();

            $users = $licensePlateUserModel->where([
                'pid' => ['in', $check_ids],
                'level' => 3
            ])->column('uid');

            $this->assign('lists', $lists);
            $this->assign('users', $users);
            return $this->fetch();
        }
    }
}